#ifndef CMD_DEAL_H
#define CMD_DEAL_H

#include <jni.h>
#include "usb_hotplug_check.h"

/*************************/
#define RX_TX_BUF_LEN 256

#define SEND_RETRY_NUM 0X03
#define SEND_TIME_OUT 0X01

/*延时 send_time_out xms*/
#define SEND_DELAY_TIME usleep(SEND_TIME_OUT * 100 * 1000)//100ms

/*串口总线协议类型定义*/
typedef enum
{
	SERIAL_BUS_MODBUS_RTU = 0X00, /*串口modbus rtu */
	SERIAL_BUS_DUYA_CURTAIN = 0X01, /*串口 duya 窗帘*/
	SERIAL_BUS_SOMFY_CURTAIN = 0X02,/*串口尚飞 窗帘*/
	SERIAL_BUS_OTHER = 0X03,
}STRU_SERIAL_BUS_PROTOCOL_TYPE;

/*当前数据帧接收状态处理流程*/
typedef enum
{
	RECV_ADDRESS_FRAME = 0X00,
	RECV_FUNCODE_FRAME = 0X01,
	RECV_DATA_FRAME = 0X02,
	RECV_CRC_FRAME = 0X03,
}STRUCT_RECV_FRAME_STEPS;

/*数据接收状态*/
typedef enum
{
	RECV_IDLE_STATUS = 0X00,
	RECV_START_STATUS = 0X01,
	RECV_FINISH_STATUS = 0X02,
	RECV_OVERFLOW_STATUS = 0X03,
	RECV_TIMEOUT_STATUS = 0x04,
	RECV_ACK_STATUS = 0X05,
}STRUCT_RECV_STATUS;

/*数据发送状态*/
typedef enum
{
	SEND_IDLE_STATUS = 0X00,
	SEND_START_STATUS = 0X01,
	SEND_FINISH_STATUS = 0X02,
	SEND_OVERFLOW_STATUS = 0X03,
	SEND_TIMEOUT_STATUS = 0x04,
	SEND_ACK_STATUS = 0X05,
}STRUCT_SEND_STATUS;

/*数据帧接收发送结构体*/
typedef struct
{
	uint8_t recvbuf[RX_TX_BUF_LEN];
	uint8_t sendbuf[RX_TX_BUF_LEN];

	uint8_t recvbuflen;
	uint8_t sendbuflen;

	uint8_t recvframelen;		//当前接收到的数据帧长度
	uint8_t sendframelen;		//当前要发送的数据帧长度

	uint8_t recvstatus;			//数据帧接收状态 :
	uint8_t sendstatus;			//数据帧发送状态 :

	uint8_t sendretrynum;		//发送重发次数
	uint8_t sendtimeout;		//发送等待超时时间

	uint8_t prototype ;
	
	/*数据帧发送、接收响应关键字段*/
	uint32_t recvdevaddr;		//
	uint32_t senddevaddr;		//

	uint16_t recvframefuncode;	//	
	uint16_t sendframefuncode;	//

	uint16_t sendframestatusregstartaddr;	//
	uint16_t sendframestatusregnum;			//
	
}STRUCT_CMD_STATUS_INFO;

//////////////////////////////////////////////////////
extern STRUCT_CMD_STATUS_INFO CmdStatusInfoStru[USB_SERIAL_AMOUNT];

/////////////////////////////外部调用接口///////////////////////
extern uint8_t cmd_init(uint8_t );
extern uint8_t cmd_send_data(int prototype,int devid,int wrtype,int datatype, int startaddr, int num,int *pdata,uint8_t channelid);
extern uint8_t cmd_recv_data(uint8_t channelid);
extern uint8_t cmd_read_data(int prototype,int devid,int wrtype,int datatype, int startaddr, int num,int * pvalue);

extern uint8_t cmd_get_send_state(uint8_t channelid);
extern uint8_t cmd_get_recv_state(uint8_t channelid);
extern uint8_t cmd_clear_send_state(uint8_t channelid,uint8_t status);
extern uint8_t cmd_clear_recv_state(uint8_t channelid,uint8_t status);
extern uint32_t cmd_wait_send_idle_state_timeout(uint8_t  channel,uint32_t delay);
uint32_t cmd_ajust_recv_timeout(uint32_t bautrate);

extern uint32_t cmd_get_device_control_channel(int prototype,uint8_t *channel);

extern int ttl_send_data(uint8_t channelid);
extern int ttl_recv_data(uint8_t channelid);

#endif
